package com.usian.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.usian.admin.feign.ArticleFeign;
import com.usian.admin.feign.SearchFeign;
import com.usian.admin.feign.WemediaFeign;
import com.usian.admin.service.AdChannelService;
import com.usian.admin.service.AdSensitiveService;
import com.usian.admin.service.WemediaNewsAutoScanService;
import com.usian.common.aliyun.GreeTextScan;
import com.usian.common.aliyun.GreenImageScan;
import com.usian.common.fastdfs.FastDFSClient;
import com.usian.common.wemedia.WemediaContans;
import com.usian.model.admin.pojos.AdChannel;
import com.usian.model.article.pojos.ApArticle;
import com.usian.model.article.pojos.ApArticleConfig;
import com.usian.model.article.pojos.ApArticleContent;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.common.constants.AdminConstans;
import com.usian.model.media.pojos.WmNews;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.SensitiveWordUtil;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
@Log4j2
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {

    @Autowired
    private AdSensitiveService adSensitiveService;
    @Autowired
    private WemediaFeign wemediaFeign;
    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private GreeTextScan greeTextScan;

    @Value("${fastdfs.url}")
    private String fastServiceUrl;
    @Autowired
    private FastDFSClient fastDFSClient;

    @Autowired
    private AdChannelService adChannelService;





    @Override
    @GlobalTransactional
    public void autoScanByMediaNewsId(Integer id) {
        if (null==id){
            log.error("传递的id为null");
            return;
        }
        WmNews wmNews=wemediaFeign.findNewsById(id);
        if (null==wmNews){
            log.error("自媒体文章为空，id为{}",id);
            return;
        }
        if (WmNews.Status.ADMIN_SUCCESS.getCode()==wmNews.getStatus().shortValue()){
            saveApArticle(wmNews);
            return;
        }

        if (WmNews.Status.SUCCESS.getCode()==wmNews.getStatus().shortValue()&& wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){


            saveApArticle(wmNews);
            return;
        }

        if (WmNews.Status.SUBMIT.getCode()==wmNews.getStatus().shortValue()){
            Map<String,Object>textAndImageMap= handleTextAndImage(wmNews);

            boolean textScanResult=
                    handleTextInAliyun((String)textAndImageMap.get(AdminConstans.CONTENT_TEXT),wmNews);
            if (!textScanResult)return;


            boolean imageScanResult=
                    handleImageScanInAliyun((List<String>)textAndImageMap.get(AdminConstans.CONTENT_IMAGES),wmNews);
            if (!imageScanResult)return;


            boolean textSensitiveResult =
                    handleTextSensitiveScan((String)textAndImageMap.get(AdminConstans.CONTENT_TEXT),wmNews);
            if (!textSensitiveResult)return;


            if (wmNews.getPublishTime().getTime()>System.currentTimeMillis()){
                updateWmNews(wmNews,WmNews.Status.SUCCESS.getCode(),"内容审核通过，待发布");
                return;
            }


            saveApArticle(wmNews);

        }
    }

    @Override
    @GlobalTransactional
    public void releaseNews(WmNews wmNews) {
        if (null==wmNews){
            log.error("自媒体文章为空");
            return;
        }

        if (WmNews.Status.SUCCESS.getCode()==wmNews.getStatus().shortValue() && wmNews.getPublishTime().getTime()<=System.currentTimeMillis()){


            saveApArticle(wmNews);
            return;
        }
    }

    //自管理敏感词检测
    private boolean handleTextSensitiveScan(String text, WmNews wmNews) {
        boolean flag=true;
        if (StringUtils.isNotBlank(text)){
            return flag;
        }
        List<String>sensitives=adSensitiveService.findAllSenstives();

        SensitiveWordUtil.initMap(sensitives);

        Map<String,Integer>resultMap=SensitiveWordUtil.matchWords(text);
        if (resultMap.size()>0){
            flag=false;
            updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"内容文本包含敏感词");

        }
        return flag;
    }


    //阿里云图片检测
    private boolean handleImageScanInAliyun(List<String> imageList,WmNews wmNews) {
        boolean flag=true;
        try {
            List<byte[]>imageByteList=new ArrayList<>();
            for (String image : imageList) {
                String fileId=image.replace(fastServiceUrl,"");
                String groupName=fileId.substring(0,fileId.indexOf("/"));
                String imagePath=fileId.substring(fileId.indexOf("/")+1);
                byte[] imageByte = fastDFSClient.download(groupName, imagePath);
                imageByteList.add(imageByte);
            }
            Map map=greenImageScan.imageScan(imageByteList);

            String suggesttion = (String) map.get("suggesttion");
            if(!suggesttion.equals("pass")){
                if (suggesttion.equals("block")){
                    updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"图片存在违规信息");
                    flag=false;
                }

                if (suggesttion.equals("review")){
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"图片可能存在违规信息，需要进一步人工审核");
                    flag=false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return flag;
    }




    //更新文章状态和审核原因
    private void updateWmNews(WmNews wmNews,Short status,String reason){
        wmNews.setStatus(status);
        wmNews.setReason(reason);
        wemediaFeign.updateNewsStatus(wmNews);
    }




    //阿里云文本检测功能
    private boolean handleTextInAliyun(String text ,WmNews wmNews) {
        boolean flag=true;
        if (StringUtils.isNotBlank(text)){
            return flag;
        }


        try {
            Map map=greeTextScan.greeTextScan(text);

            String suggesttion = (String) map.get("suggesttion");
            if(!suggesttion.equals("pass")){
                if (suggesttion.equals("block")){
                    updateWmNews(wmNews,WmNews.Status.FAIL.getCode(),"内容存在违规信息");
                    flag=false;
                }

                if (suggesttion.equals("review")){
                    updateWmNews(wmNews,WmNews.Status.ADMIN_AUTH.getCode(),"内容可能存在违规信息，需要进一步人工审核");
                    flag=false;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.error("文本审核出现异常，信息如下：{}",e.getMessage());
            flag=false;
        }

        return flag;
    }

    private Map<String, Object> handleTextAndImage(WmNews wmNews) {
        String content = wmNews.getContent();
        Map<String,Object>resultMap=new HashMap<>();
        StringBuilder textSb = new StringBuilder();
        List<String>imageList=new ArrayList<>();
        List<Map>maps= JSON.parseArray(content,Map.class);
        for (Map map : maps) {
            if (map.get(AdminConstans.CONTENT_TYPE).equals(AdminConstans.CONTENT_TEXT)){
                textSb.append(map.get(AdminConstans.CONTENT_VALUE));
            }else if (map.get(AdminConstans.CONTENT_TYPE).equals(AdminConstans.CONTENT_IMAGE)){
                imageList.add((String) map.get(AdminConstans.CONTENT_VALUE));
            }
        }
        if (StringUtils.isNotBlank(wmNews.getImages()) &&
                wmNews.getType().shortValue() !=WemediaContans.WM_NEWS_NONE_IMAGE.shortValue()){
            String[] sp=wmNews.getImages().split(",");
            imageList.addAll(Arrays.asList(sp));
        }
        resultMap.put(AdminConstans.CONTENT_TEXT,textSb.toString());
        resultMap.put(AdminConstans.CONTENT_IMAGES,imageList);
        return resultMap;
    }


    private void saveApArticle(WmNews wmNews){
        ApArticle apArticle = saveArticle(wmNews);

        saveApArticleConfig(apArticle.getId());

        saveApArticleContent(apArticle.getId(),wmNews.getContent());


        importES(apArticle,wmNews);

        wmNews.setArticleId(apArticle.getId());
        updateWmNews(wmNews,WmNews.Status.PUBLISHED.getCode(),"文章审核通过，已发布");
    }

    @Autowired
    private SearchFeign searchFeign;

    public void importES(ApArticle apArticle,WmNews wmNews){

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id", apArticle.getId());
        map.put("publishTime", apArticle.getPublishTime());
        map.put("layout", apArticle.getLayout());
        map.put("images", apArticle.getImages());
        map.put("authorId", apArticle.getAuthorId());
        map.put("title", apArticle.getTitle());
        map.put("content",wmNews.getContent());
        searchFeign.importData(map);


    }



    private void saveApArticleContent(Long articelId, String content) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(articelId);
        apArticleContent.setContent(content);
        articleFeign.saveArticleContent(apArticleContent);
    }

    private void saveApArticleConfig(Long articelId) {
        ApArticleConfig apArticleConfig=new ApArticleConfig();
        apArticleConfig.setArticleId(articelId);
        apArticleConfig.setIsComment(true);
        apArticleConfig.setIsComment(false);
        apArticleConfig.setIsDown(false);
        apArticleConfig.setIsForward(true);
        articleFeign.saveArticleConfig(apArticleConfig);
    }


    //保存ap/_article
    private ApArticle saveArticle(WmNews wmNews) {
        ApArticle apArticle=new ApArticle();

        apArticle.setTitle(wmNews.getTitle());
        WmUser wmUser=wemediaFeign.findUserById(wmNews.getUserId());
        ApAuthor apAuthor=articleFeign.findByName(wmUser.getName());
        if (apAuthor!=null){
            apArticle.setAuthorId(apAuthor.getId().longValue());
            apArticle.setAuthorName(apAuthor.getName());
        }

        AdChannel adChannel=adChannelService.getById(wmNews.getChannelId());

        if (adChannel!=null){
            apArticle.setChannelId(adChannel.getId());
            apArticle.setAuthorName(adChannel.getName());
        }
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setLabels(wmNews.getLabels());
        apArticle.setCreatedTime(new Date());
        apArticle.setPublishTime(new Date());

        apArticle = articleFeign.saveArticle(apArticle);
        return apArticle;

    }
}
